<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="优惠券名称">
          <el-input 
            v-model="queryParams.couponName" 
            placeholder="请输入优惠券名称" 
            clearable 
          />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="queryParams.couponType" placeholder="请选择优惠券类型" clearable>
            <el-option label="满减券" value="0" />
            <el-option label="折扣券" value="1" />
            <el-option label="免费券" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未发布" value="0" />
            <el-option label="发布中" value="1" />
            <el-option label="已结束" value="2" />
            <el-option label="已停用" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">创建优惠券</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="couponList"
      border
      style="width: 100%"
    >
      <el-table-column prop="couponId" label="ID" width="80" align="center" />
      <el-table-column prop="couponName" label="优惠券名称" min-width="150" />
      <el-table-column label="类型" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getCouponTypeTagType(scope.row.couponType)">
            {{ getCouponTypeText(scope.row.couponType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠信息" width="150" align="center">
        <template #default="scope">
          <div v-if="scope.row.couponType === '0'">
            满{{ scope.row.minAmount }}减{{ scope.row.discountAmount }}
          </div>
          <div v-else-if="scope.row.couponType === '1'">
            {{ (scope.row.discountRate * 10).toFixed(1) }}折
            <br>
            <span class="text-xs text-gray-500">
              最高减{{ scope.row.maxDiscountAmount }}
            </span>
          </div>
          <div v-else>
            免费券
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="minAmount" label="最低消费" width="100" align="center">
        <template #default="scope">
          ¥{{ scope.row.minAmount }}
        </template>
      </el-table-column>
      <el-table-column label="发放数量" width="120" align="center">
        <template #default="scope">
          <div>
            <div>总量：{{ scope.row.totalCount }}</div>
            <div class="text-green-500">剩余：{{ scope.row.remainCount }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="limitPerUser" label="限领数量" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期" width="160">
        <template #default="scope">
          <div class="text-sm">
            <div>{{ scope.row.startTime }}</div>
            <div>{{ scope.row.endTime }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            v-if="scope.row.status === '0'" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '1')"
          >
            发布
          </el-button>
          <el-button 
            v-if="scope.row.status === '1'" 
            type="warning" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '3')"
          >
            停用
          </el-button>
          <el-button 
            v-if="scope.row.status === '3'" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, '1')"
          >
            启用
          </el-button>
          <el-button 
            v-if="scope.row.status === '0'" 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 优惠券表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="请选择优惠券类型" @change="handleTypeChange">
            <el-option label="满减券" value="0" />
            <el-option label="折扣券" value="1" />
            <el-option label="免费券" value="2" />
          </el-select>
        </el-form-item>
        
        <!-- 满减券字段 -->
        <template v-if="form.couponType === '0'">
          <el-form-item label="减免金额" prop="discountAmount">
            <el-input-number v-model="form.discountAmount" :min="0" :precision="2" :step="1" />
            <span class="ml-2 text-gray-500">元</span>
          </el-form-item>
        </template>
        
        <!-- 折扣券字段 -->
        <template v-if="form.couponType === '1'">
          <el-form-item label="折扣率" prop="discountRate">
            <el-input-number v-model="form.discountRate" :min="0.1" :max="1" :precision="2" :step="0.1" />
            <span class="ml-2 text-gray-500">（0.1-1.0，如0.8表示8折）</span>
          </el-form-item>
          <el-form-item label="最高减免" prop="maxDiscountAmount">
            <el-input-number v-model="form.maxDiscountAmount" :min="0" :precision="2" :step="1" />
            <span class="ml-2 text-gray-500">元</span>
          </el-form-item>
        </template>
        
        <!-- 通用字段 -->
        <el-form-item v-if="form.couponType !== '2'" label="最低消费" prop="minAmount">
          <el-input-number v-model="form.minAmount" :min="0" :precision="2" :step="1" />
          <span class="ml-2 text-gray-500">元</span>
        </el-form-item>
        
        <el-form-item label="发放总量" prop="totalCount">
          <el-input-number v-model="form.totalCount" :min="1" :precision="0" />
          <span class="ml-2 text-gray-500">张</span>
        </el-form-item>
        
        <el-form-item label="每人限领" prop="limitPerUser">
          <el-input-number v-model="form.limitPerUser" :min="1" :precision="0" />
          <span class="ml-2 text-gray-500">张</span>
        </el-form-item>
        
        <el-form-item label="有效期开始" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="有效期结束" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCouponPage, 
  createCoupon, 
  updateCoupon,
  deleteCoupon,
  updateCouponStatus
} from '@/api/coupon'
import { handlePageResponse } from '@/utils/pagination'

// 优惠券列表
const couponList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('创建优惠券')
// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  couponName: '',
  couponType: '',
  status: ''
})

// 表单数据
const form = reactive({
  couponId: null,
  couponName: '',
  couponType: '',
  discountAmount: 0,
  discountRate: 0.8,
  minAmount: 0,
  maxDiscountAmount: 0,
  totalCount: 100,
  limitPerUser: 1,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const rules = {
  couponName: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  couponType: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  discountAmount: [
    { required: true, message: '请输入减免金额', trigger: 'blur' }
  ],
  discountRate: [
    { required: true, message: '请输入折扣率', trigger: 'blur' }
  ],
  minAmount: [
    { required: true, message: '请输入最低消费金额', trigger: 'blur' }
  ],
  maxDiscountAmount: [
    { required: true, message: '请输入最高减免金额', trigger: 'blur' }
  ],
  totalCount: [
    { required: true, message: '请输入发放总量', trigger: 'blur' }
  ],
  limitPerUser: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择有效期开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择有效期结束时间', trigger: 'change' }
  ]
}

// 获取优惠券类型文本
const getCouponTypeText = (type) => {
  const typeMap = {
    '0': '满减券',
    '1': '折扣券',
    '2': '免费券'
  }
  return typeMap[type] || '未知类型'
}

// 获取优惠券类型标签类型
const getCouponTypeTagType = (type) => {
  const typeMap = {
    '0': 'primary',
    '1': 'success',
    '2': 'warning'
  }
  return typeMap[type] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '未发布',
    '1': '发布中',
    '2': '已结束',
    '3': '已停用'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '0': 'info',
    '1': 'success',
    '2': 'warning',
    '3': 'danger'
  }
  return statusMap[status] || ''
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取优惠券列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getCouponPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    couponList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.couponName = ''
  queryParams.couponType = ''
  queryParams.status = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加优惠券
const handleAdd = () => {
  dialogTitle.value = '创建优惠券'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑优惠券
const handleEdit = (row) => {
  dialogTitle.value = '编辑优惠券'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理类型变化
const handleTypeChange = (type) => {
  // 根据类型重置相关字段
  if (type === '0') { // 满减券
    form.discountRate = 0
    form.maxDiscountAmount = 0
  } else if (type === '1') { // 折扣券
    form.discountAmount = 0
    form.discountRate = 0.8
  } else if (type === '2') { // 免费券
    form.discountAmount = 0
    form.discountRate = 0
    form.minAmount = 0
    form.maxDiscountAmount = 0
  }
}

// 处理删除优惠券
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认要删除优惠券"${row.couponName}"吗？此操作将永久删除该优惠券，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteCoupon(row.couponId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      fetchData()
    } catch (error) {
      console.error('删除优惠券失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 处理更新优惠券状态
const handleUpdateStatus = (row, status) => {
  const statusText = getStatusText(status)
  ElMessageBox.confirm(
    `确认将优惠券"${row.couponName}"设为${statusText}状态吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      await updateCouponStatus(row.couponId, status)
      ElMessage({
        type: 'success',
        message: `状态更新成功!`
      })
      fetchData()
    } catch (error) {
      console.error('更新优惠券状态失败:', error)
      ElMessage({
        type: 'error',
        message: '状态更新失败'
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  form.couponId = null
  form.couponName = ''
  form.couponType = ''
  form.discountAmount = 0
  form.discountRate = 0.8
  form.minAmount = 0
  form.maxDiscountAmount = 0
  form.totalCount = 100
  form.limitPerUser = 1
  form.startTime = ''
  form.endTime = ''
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    // 验证时间
    if (form.startTime >= form.endTime) {
      ElMessage.error('结束时间必须大于开始时间')
      return
    }
    
    submitLoading.value = true
    try {
      if (form.couponId) {
        await updateCoupon(form)
        ElMessage({
          type: 'success',
          message: '更新成功!'
        })
      } else {
        await createCoupon(form)
        ElMessage({
          type: 'success',
          message: '创建成功!'
        })
      }
      dialogVisible.value = false
      fetchData()
    } catch (error) {
      console.error('保存优惠券失败:', error)
      ElMessage({
        type: 'error',
        message: '保存失败，请稍后再试'
      })
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.text-xs {
  font-size: 12px;
}

.text-sm {
  font-size: 14px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-green-500 {
  color: #10b981;
}

.ml-2 {
  margin-left: 8px;
}
</style>

